Trading at Alpaca





Kerry Back

Create alpaca account

  • After logging in to Alpaca, you DO NOT need to enter name, address, etc. - that is only for real trading accounts.
  • By clicking the Overview icon on the left toolbar, you should get to the screen on the following slide.
  • Click on API Keys, then Regenerate to see your key and your secret key. Copy and save them somewhere.

Install alpaca-py

Connect to alpaca

from alpaca.trading.client import TradingClient
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce

KEY = "your_key"
SECRET_KEY = "your_secret_key"

data_client = StockHistoricalDataClient(KEY, SECRET_KEY)
trading_client = TradingClient(KEY, SECRET_KEY, paper=True)

Send a trade

market_order_data = MarketOrderRequest(
    symbol="AAPL",
    qty=10,
    side=OrderSide.BUY,
    time_in_force=TimeInForce.DAY
    )
market_order = trading_client.submit_order(
        order_data=market_order_data
    )

Check your positions

positions = trading_client.get_all_positions()
positions
[{   'asset_class': <AssetClass.US_EQUITY: 'us_equity'>,
     'asset_id': UUID('b0b6dd9d-8b9b-48a9-ba46-b9d54906e415'),
     'avg_entry_price': '132.94',
     'change_today': '-0.0020226234174845',
     'cost_basis': '1329.4',
     'current_price': '133.22',
     'exchange': <AssetExchange.NASDAQ: 'NASDAQ'>,
     'lastday_price': '133.49',
     'market_value': '1332.2',
     'qty': '10',
     'side': <PositionSide.LONG: 'long'>,
     'symbol': 'AAPL',
     'unrealized_intraday_pl': '2.8',
     'unrealized_intraday_plpc': '0.0021062133293215',
     'unrealized_pl': '2.8',
     'unrealized_plpc': '0.0021062133293215'}]